/**
 * @file context.c
 *
 * Copyright (C) Huawei Technologies Co., Ltd. 2023. All Rights Reserved.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#include "acl/acl_rt.h"
#include "log_inner.h"
#include "runtime/rt.h"

#if defined(__cplusplus)
extern "C" {
#endif

aclError aclrtCreateContext(aclrtContext *context, int32_t deviceId) {
  if (context == NULL) {
    ACL_LOG_ERROR("ctx is null");
    return ACL_ERROR_INVALID_PARAM;
  }

  rtContext_t rtCtx = NULL;
  const rtError_t rtErr =
    rtCtxCreateEx(&rtCtx, (uint32_t)(RT_CTX_NORMAL_MODE), deviceId);
  if (rtErr != RT_ERROR_NONE) {
    ACL_LOG_CALL_ERROR(
        "create context failed, device is %d, ret=%d",
        deviceId, (int32_t)(rtErr));
    return rtErr;
  }

  *context = (aclrtContext)(rtCtx);
  return ACL_SUCCESS;
}

aclError aclrtDestroyContext(aclrtContext context) {
  if (context == NULL) {
    ACL_LOG_ERROR("ctx is null");
    return ACL_ERROR_INVALID_PARAM;
  }
  const rtError_t rtErr = rtCtxDestroyEx((rtContext_t)(context));
  if (rtErr != RT_ERROR_NONE) {
    ACL_LOG_CALL_ERROR("destory context failed, ret=%d",
                       (int32_t)(rtErr));
    return rtErr;
  }
  return ACL_SUCCESS;
}

aclError aclrtSetCurrentContext(aclrtContext context) {
  if (context == NULL) {
    ACL_LOG_ERROR("ctx is null");
    return ACL_ERROR_INVALID_PARAM;
  }
  const rtError_t rtErr = rtCtxSetCurrent((rtContext_t)(context));
  if (rtErr != RT_ERROR_NONE) {
    ACL_LOG_CALL_ERROR("set current context failed, ret=%d",
                       (int32_t)(rtErr));
    return rtErr;
  }
  return ACL_SUCCESS;
}

aclError aclrtGetCurrentContext(aclrtContext *context) {
  if (context == NULL) {
    ACL_LOG_ERROR("ctx is null");
    return ACL_ERROR_INVALID_PARAM;
  }

  rtContext_t rtCtx = NULL;
  const rtError_t rtErr = rtCtxGetCurrent(&rtCtx);
  if (rtErr != RT_ERROR_NONE) {
    ACL_LOG_INFO("can not get current context, ret=%d",
                 (int32_t)(rtErr));
    return rtErr;
  }

  *context = rtCtx;
  return ACL_SUCCESS;
}

#if defined(__cplusplus)
}
#endif